/**
 * @author kaho
 * @since 2021/3/16
 */
public class _59_螺旋矩阵II {

    /**
     * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
     * @param n
     * @return
     */
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int cur = 0;
        int top = 0, bottom = n-1, left = 0, right =n-1;
        while (top<=bottom && left<=right){
            for (int i = left; i <= right; i++) {
                result[top][i] = ++cur;
            }
            for (int i = top+1; i <= bottom; i++) {
                result[i][right] = ++cur;
            }

            if (top<bottom&&left<right){
                for (int i = right-1; i >= left; i--) {
                    result[bottom][i] = ++cur;
                }

                for (int i = bottom-1; i > top; i--) {
                    result[i][left] = ++cur;
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return result;
    }
}
